package com.sale.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.core.utils.StringUtils;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.RemoteUnitService;
import com.sale.system.api.domain.dto.MaterialAuxiliaryDto;
import com.sale.system.api.model.MaterialUnitDto;
import com.sale.system.domain.MaterialAuxiliary;
import com.sale.system.domain.MaterialWaste;
import com.sale.system.domain.SysAuxiliaryUnitDetail;
import com.sale.system.domain.dto.MaterialAccessoriesDto;
import com.sale.system.domain.dto.MaterialWasteDto;
import com.sale.system.domain.dto.SysCategoryDto;
import com.sale.system.domain.dto.SysTheDropDto;
import com.sale.system.domain.vo.MaterialMqMessageVo;
import com.sale.system.domain.vo.MaterialWasteVo;
import com.sale.system.mapper.MaterialAuxiliaryMapper;
import com.sale.system.mapper.MaterialWasteMapper;
import com.sale.system.mapper.SysAuxiliaryUnitDetailMapper;
import com.sale.system.mapper.SysAuxiliaryUnitMapper;
import com.sale.system.service.IMaterialWasteService;
import com.sale.system.service.ISysCategoryService;
import com.sale.system.service.ISysDocumentService;
import com.sale.system.service.ISysMidSplitService;
import com.sale.system.util.MaterialMqUtil;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

import static org.apache.poi.sl.usermodel.PlaceholderDetails.PlaceholderSize.half;

/**
 * @Description 废料信息
 * @Date 22-11-24
 * @Author hl
 **/
@RequiredArgsConstructor
@Service
public class MaterialWasteServiceImpl implements IMaterialWasteService {

    private final MaterialWasteMapper materialWasteMapper;

    private final SysAuxiliaryUnitMapper sysAuxiliaryUnitMapper;

    private final MaterialAuxiliaryMapper materialAuxiliaryMapper;

    private final ISysDocumentService sysDocumentService;

    private final SysAuxiliaryUnitDetailMapper sysAuxiliaryUnitDetailMapper;

    @DubboReference
    RemoteUnitService remoteUnitService;

    private final ISysCategoryService sysCategoryService;

    private final ISysMidSplitService sysMidSplitService;

    /**
     * 获取废料配置
     */
    @Override
    public TableDataInfo<MaterialWasteDto> selectWasteList(MaterialWasteVo materialWasteVo, PageQuery pageQuery) {
        Page<MaterialWasteDto> page = materialWasteMapper.selectWasteList(pageQuery.build(), this.buildQueryWrapper(materialWasteVo));
        List<MaterialWasteDto> list = page.getRecords();
        //渲染辅助属性
//        // 多单位
//        List<SysTheDropDto> listThe = sysAuxiliaryUnitMapper.selectMultiMeteringUnitAllList();
//        Map<String, String> map = listThe.stream()
//            .collect(Collectors.toMap(SysTheDropDto::getValue, SysTheDropDto::getLabel));

        //单位集合
        Map<String, MaterialUnitDto> unitByCodeToMap = remoteUnitService.getUnitByCodeToMap();

        for (MaterialWasteDto dto :
            list) {
            // String unit = dto.getMaterialUnit();
            //if (unit != null) {
            //  dto.setMaterialUnitDict(unitByCodeToMap.get(unit).getUnitName());
            //   }
            dto.setAuxiliaryAttribute(materialAuxiliaryMapper.selectAuxiliaryById(dto.getMaterialId()));
        }
        return TableDataInfo.build(page);
    }

    private Wrapper<MaterialWasteVo> buildQueryWrapper(MaterialWasteVo materialWasteVo) {
        Map<String, Object> params = materialWasteVo.getParams();
        QueryWrapper<MaterialWasteVo> wrapper = Wrappers.query();
        wrapper
            .like(ObjectUtil.isNotNull(materialWasteVo.getMaterialCode()), "t1.material_code", materialWasteVo.getMaterialCode())
            .like(StringUtils.isNotBlank(materialWasteVo.getMaterialName()), "t1.material_name", materialWasteVo.getMaterialName())
            .eq(StringUtils.isNotBlank(materialWasteVo.getMaterialStatus()), "t1.material_status", materialWasteVo.getMaterialStatus())
            .between(params.get("beginTime") != null && params.get("endTime") != null,
                "t1.create_time", params.get("beginTime"), params.get("endTime"));
        return wrapper;
    }

    /**
     * 新增废料信息
     */
    @Override
    public int insertWaste(MaterialWasteVo materialWasteVo) throws Exception {
        MaterialWaste waste = new MaterialWaste();
        BeanUtils.copyProperties(materialWasteVo, waste);
        List<SysAuxiliaryUnitDetail> list2 = materialWasteVo.getList();
        StringBuffer moreUnit = new StringBuffer();
        waste.setMaterialId(IdWorker.getId());
        for (SysAuxiliaryUnitDetail item : list2) {
            moreUnit.append(item.getAuxiliaryId()).append(",");
            item.setMaterialId(waste.getMaterialId());
        }
        waste.setMaterialMoreUnit(moreUnit.toString().substring(0, moreUnit.length() - 1));
        //废料编码按照类别配置中得生成
        SysCategoryDto sysCategoryDto = sysCategoryService.selectCategoryById(materialWasteVo.getMaterialType());
        String s = sysMidSplitService.selectSplitStr(sysCategoryDto.getCodeRule());
        if (StringUtils.isEmpty(s)) {
            throw new GlobalException("编码生成失败，请检查配置");
        }
        waste.setMaterialCode(s);
        waste.setCreateBy(LoginHelper.getUsername());
        //mq发送消息
  /*      String userIdStr = LoginHelper.getUserIdStr();
        MaterialMqMessageVo materialMqVo = new MaterialMqMessageVo();
        BeanUtils.copyProperties(waste, materialMqVo);
        materialMqVo.setUserIdStr(userIdStr);
        materialMqVo.setMaterialType(Long.parseLong(String.valueOf(waste.getMaterialType())));
        MaterialMqUtil.materialMqSend(materialMqVo);*/

        int i = materialWasteMapper.insert(waste);
        List<MaterialAuxiliary> list = materialWasteVo.getAuxiliaryAttribute();
        if (list != null) {
            for (MaterialAuxiliary auxiliary :
                list) {
                auxiliary.setMaterialId(waste.getMaterialId());
                auxiliary.setAuxiliaryId(IdWorker.getId());
            }
            materialAuxiliaryMapper.insertBatch(list);
        }
        if (list2.get(0).getAuxiliaryId() != null) {
            sysAuxiliaryUnitDetailMapper.insertBatch(list2);
        }
        return i;
    }

    /**
     * 删除废料信息
     */
    @Override
    public int deleteWasteById(String materialId) throws Exception {
        String[] materialIdS = materialId.split(",");
        ArrayList<String> arrayList = new ArrayList<>();
        for (String str :
            materialIdS) {
            arrayList.add(str);
            //删除对应属性
            HashMap<String, Object> map = new HashMap<>();
            map.put("material_id", str);
            materialAuxiliaryMapper.deleteByMap(map);
            sysAuxiliaryUnitDetailMapper.deleteByMap(map);
        }
        //mq发送消息(删除)
        MaterialMqMessageVo materialMqVo = new MaterialMqMessageVo();
        materialMqVo.setIdStr(materialId);
        MaterialMqUtil.materialMqSendDelete(materialMqVo);
        return materialWasteMapper.deleteBatchIds(Arrays.asList(materialIdS));
    }

    /**
     * 根据编号获取详细信息
     */
    @Override
    public MaterialWasteDto selectWasteById(long materialId) {
        MaterialWaste waste = materialWasteMapper.selectById(materialId);
        MaterialWasteDto dto = new MaterialWasteDto();
        BeanUtils.copyProperties(waste, dto);
        List<MaterialAuxiliaryDto> list = materialAuxiliaryMapper.selectAuxiliaryById(materialId);
        dto.setAuxiliaryAttribute(list);
        Map<String, Object> map = new HashMap<>();
        map.put("material_id", materialId);
        dto.setList(sysAuxiliaryUnitDetailMapper.selectByMap(map));
        return dto;
    }

    /**
     * 修改废料信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateWasteEdit(MaterialWasteVo materialWasteVo) throws Exception {
        MaterialWaste waste = new MaterialWaste();
        BeanUtils.copyProperties(materialWasteVo, waste);
        List<SysAuxiliaryUnitDetail> list2 = materialWasteVo.getList();
        StringBuffer moreUnit = new StringBuffer();
        for (SysAuxiliaryUnitDetail item : list2) {
            moreUnit.append(item.getAuxiliaryId()).append(",");
            item.setMaterialId(waste.getMaterialId());
        }
        if (StringUtils.isNotEmpty(moreUnit.toString())) {
            waste.setMaterialMoreUnit(moreUnit.toString().substring(0, moreUnit.length() - 1));
        }
        int i = materialWasteMapper.updateById(waste);
        //mq发送消息
        String userIdStr = LoginHelper.getUserIdStr();
        MaterialMqMessageVo materialMqVo = new MaterialMqMessageVo();
        BeanUtils.copyProperties(waste, materialMqVo);
        materialMqVo.setMaterialId(waste.getMaterialId());
        materialMqVo.setUserIdStr(userIdStr);
        materialMqVo.setMaterialType(Long.parseLong(String.valueOf(waste.getMaterialType())));
        MaterialMqUtil.materialMqSend(materialMqVo);
        List<MaterialAuxiliary> list = materialWasteVo.getAuxiliaryAttribute();
        if (list != null) {
            //删除对应属性
            HashMap<String, Object> map = new HashMap<>();
            long materialId = waste.getMaterialId();
            map.put("material_id", materialId);
            materialAuxiliaryMapper.deleteByMap(map);
            sysAuxiliaryUnitDetailMapper.deleteByMap(map);
            //重新新增对应属性
            for (MaterialAuxiliary auxiliary :
                list) {
                auxiliary.setMaterialId(materialId);
                auxiliary.setAuxiliaryId(IdWorker.getId());
            }
            //批量新增物料属性信息
            materialAuxiliaryMapper.insertBatch(list);
        }
        if (list2.size() > 0) {
            sysAuxiliaryUnitDetailMapper.insertBatch(list2);
        }
        return i;
    }

    /**
     * 废料冻结
     */
    @Override
    public int updateEditFreeze(Long materialId) {
        MaterialWaste waste = new MaterialWaste();
        waste.setMaterialId(materialId);
        waste.setMaterialStatus(1);
        return materialWasteMapper.updateById(waste);
    }

    /**
     * 废料解冻
     */
    @Override
    public int updateEditThaw(Long materialId) {
        MaterialWaste waste = new MaterialWaste();
        waste.setMaterialId(materialId);
        waste.setMaterialStatus(2);
        return materialWasteMapper.updateById(waste);
    }
}
